package com.yoda.mall.admin.service;

import cn.hutool.core.util.ObjectUtil;
import com.yoda.mall.api.FlashPromotionProductRelationApi;
import com.yoda.mall.api.FlashPromotionSessionApi;
import com.yoda.mall.model.entity.sms.FlashPromotionSession;
import com.yoda.mall.model.vo.FlashPromotionSessionVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class FlashSessionService {
    @DubboReference
    private FlashPromotionSessionApi flashPromotionSessionApi;
    @DubboReference
    private FlashPromotionProductRelationApi flashPromotionProductRelationApi;

    public void createFlashPromotionSession(FlashPromotionSession flashPromotionSession) {
        flashPromotionSessionApi.createFlashPromotionSession(flashPromotionSession);
    }

    public void deleteFlashPromotionSession(Long id) {
        flashPromotionSessionApi.deleteFlashPromotionSessionById(id);
    }

    public List<FlashPromotionSession> flashPromotionSessionList() {
        return flashPromotionSessionApi.getAllFlashPromotionSession();
    }

    public List<FlashPromotionSessionVo> flashPromotionSessionVoList(Long flashPromotionId) {
        List<Long> FlashPromotionSessionIds = flashPromotionProductRelationApi.getFlashPromotionSessionsIdByFlashPromotionId(flashPromotionId);
        if(ObjectUtil.isEmpty(FlashPromotionSessionIds)){
            return new ArrayList<>();
        }
        List<FlashPromotionSession> list = flashPromotionSessionApi.getFlashPromotionSessionsByIds(FlashPromotionSessionIds);
        return list.stream().map(flashPromotionSession -> {
            Long count = flashPromotionProductRelationApi.getCountByFlashPromotionIdAndFlashPromotionSessionId(flashPromotionId, flashPromotionSession.getId());
            FlashPromotionSessionVo flashPromotionSessionVo = new FlashPromotionSessionVo();
            BeanUtils.copyProperties(flashPromotionSession, flashPromotionSessionVo);
            flashPromotionSessionVo.setProductCount(count);
            return flashPromotionSessionVo;
        }).collect(Collectors.toList());
    }

    public void updateFlashPromotionSessionStatus(Long id, Integer status) {
        FlashPromotionSession flashPromotionSession = new FlashPromotionSession();
        flashPromotionSession.setId(id);
        flashPromotionSession.setStatus(status);
        flashPromotionSessionApi.updateFlashPromotionSession(flashPromotionSession);
    }

    public void updateFlashPromotionSession(Long id, FlashPromotionSession flashPromotionSession) {
        flashPromotionSession.setId(id);
        flashPromotionSessionApi.updateFlashPromotionSession(flashPromotionSession);
    }

    public FlashPromotionSession getFlashPromotionSession(Long id) {
        return flashPromotionSessionApi.getFlashPromotionSessionById(id);
    }
}
